from django.shortcuts import render, redirect
from django.contrib.auth import login, logout
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.conf import settings
from django.contrib.auth.models import User

import requests

from .models import OAuth


def login_view(request, *args, **kwargs):
    form = AuthenticationForm(request, data=request.POST or None)
    if form.is_valid():
        user_ = form.get_user()
        login(request, user_)
        return redirect("/")
    # 请求到github登陆的url 在页面上 用户点击会发送get请求到github
    github_oauth_url = settings.GITHUB_REQUEST_URL + \
        '?client_id={}'.format(settings.GITHUB_CLIENT_ID)
    context = {
        "form": form,
        "btn_label": "Login",
        "title": "Login",
        "github_oauth_url": github_oauth_url
    }
    return render(request, "accounts/auth.html", context)


def logout_view(request, *args, **kwargs):
    if request.method == "POST":
        logout(request)
        return redirect("/login")
    context = {
        "form": None,
        "description": "Are you sure you want to logout?",
        "btn_label": "Click to Confirm",
        "title": "Logout"
    }
    return render(request, "accounts/auth.html", context)


def register_view(request, *args, **kwargs):
    form = UserCreationForm(request.POST or None)
    if form.is_valid():
        user = form.save(commit=True)
        user.set_password(form.cleaned_data.get("password1"))
        # send a confirmation email to verify their account
        login(request, user)
        return redirect("/")
    context = {
        "form": form,
        "btn_label": "Register",
        "title": "Register"
    }
    return render(request, "accounts/auth.html", context)

# 1. 拿到code
# 2. 发送post请求 拿到access_token


def github_oauth_view(request, *args, **kwargs):
    code = request.GET.get('code')
    if not code:
        return PermissionError
    # 获取access_token
    access_token_url = settings.GITHUB_ACCESS_TOKEN_URL
    client_id = settings.GITHUB_CLIENT_ID
    client_secret = settings.GITHUB_SECRET
    headers = {'Accept': 'application/json'}
    data = {
        'client_id': client_id,
        'client_secret': client_secret,
        'code': code
    }
    r = requests.post(access_token_url, data=data, headers=headers)
    res = r.json()
    access_token = res.get('access_token')
    if not access_token:
        raise PermissionError

    # 获取用户信息
    user_api = settings.GITHUB_USER_INFO_URL + '?access_token={}'.format(access_token)
    r = requests.get(url=user_api)
    user_info = r.json()
    github_id = user_info['id']
    username = user_info['login']
    
    # print('github_id = {} username = {}'.format(github_id, username))

    # 查询用户是否存在
    user = User.objects.filter(oauth__github_id=github_id)
    if not user:
        user = User.objects.create_user(username)
        oauth = OAuth(
            user=user,
            github_id=github_id
        )
        oauth.save()
    else:
        user = user.first()
    login(request, user)
    return redirect('/')